// RocksDBWrapper.h
#ifndef ROCKSDB_WRAPPER_H
#define ROCKSDB_WRAPPER_H

#include <rocksdb/db.h>
#include <rocksdb/options.h>
#include <rocksdb/slice.h>
#include <rocksdb/write_batch.h>
#include <functional>
#include <iostream>
#include <string>

class RocksDBWrapper
{
public:
    RocksDBWrapper(const std::string &db_path)
        : db_path_(db_path), db_(nullptr)
    {
        // 初始化存储引擎选项
        options_.create_if_missing = true;
        // 可以添加更多选项配置
    }

    ~RocksDBWrapper()
    {
        if (db_ != nullptr)
        {
            db_->Close();
            delete db_;
        }
    }

    // 打开存储引擎
    bool open()
    {
        rocksdb::Status status = rocksdb::DB::Open(options_, db_path_, &db_);
        return status.ok();
    }

    // 写入
    bool put(const std::string &key, const std::string &value)
    {
        return db_->Put(rocksdb::WriteOptions(), key, value).ok();
    }

    // 同步写入，或称为同步刷盘，意味着在数据被写入内存后，会等待操作系统将数据刷新到磁盘上完成。
    // 在 RocksDB 中，可以通过设置 WriteOptions 的 sync 属性为 true 来启用同步写入：
    bool syncPut(const std::string &key, const std::string &value)
    {
        rocksdb::WriteOptions write_options;
        write_options.sync = true;
        return db_->Put(write_options, key, value).ok();
    }

    // 读取
    bool get(const std::string &key, std::string &value)
    {
        return db_->Get(rocksdb::ReadOptions(), key, &value).ok();
    }

    // 删除
    bool remove(const std::string &key)
    {
        return db_->Delete(rocksdb::WriteOptions(), key).ok();
    }

    // 原子更新
    bool atomicUpdate(const std::string &key1, const std::string &key2)
    {
        // 使用WriteBatch来实现原子更新
        std::string value;
        rocksdb::Status s = db_->Get(rocksdb::ReadOptions(), key1, &value);
        if (s.ok())
        {
            rocksdb::WriteBatch batch;
            batch.Delete(key1);
            batch.Put(key2, value);
            // 提交这个 WriteBatch，上面的两个操作要么都成功要么都失败
            return db_->Write(rocksdb::WriteOptions(), &batch).ok();
        }
        std::cout << "no value in key1" << std::endl;
        return s.ok();
    }

    // 异步写入接口需要自定义线程安全的写入队列和写入者线程

    // 迭代器遍历
    void traverse()
    {
        rocksdb::Iterator *it = db_->NewIterator(rocksdb::ReadOptions());
        for (it->SeekToFirst(); it->Valid(); it->Next())
        {
            std::cout << it->key().ToString() << ": " << it->value().ToString() << std::endl;
        }
        assert(it->status().ok()); // Check for any errors found during the scan
        delete it;
    }

    // 获得快照
    const rocksdb::Snapshot *getSnapshot()
    {
        return db_->GetSnapshot();
    }

private:
    std::string db_path_;
    rocksdb::DB *db_;
    rocksdb::Options options_;
};

#endif // ROCKSDB_WRAPPER_H